# Title     : TODO
# Objective : TODO
# Created by: yz
# Created on: 2018/3/1

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

library(optparse)
library(magrittr)
library(tidyverse)
library(extrafont)

option_list <- list(
  make_option("--pc", default = "", type = "character", help = "config file")

)
opt <- parse_args(OptionParser(option_list = option_list))
font_import(paths = c("/usr/share/fonts/myFonts"), recursive = F, prompt = F)

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))
source(str_c(scriptPath, "/parse_config_json.R"))
baseFamily <- fontFamily
fileName <- "enrich_mSet.RData"
if (!file.exists(fileName)) {
  quit(status = 0)
}else {
  load(fileName)
}


parent <- "./"
createWhenNoExist(parent)

if (!is.numeric(inMset)) {
  imageName <- str_c(parent, "/Enrichment_Barplot.pdf")
  mSetObj <- inMset
  mSetObj <- .get.mSet(mSetObj)
  folds <- mSetObj$analSet$ora.mat[, 3] / mSetObj$analSet$ora.mat[,
    2]
  # names(folds) <- GetShortNames(rownames(mSetObj$analSet$ora.mat))
  names(folds) <- (rownames(mSetObj$analSet$ora.mat))
  pvals <- mSetObj$analSet$ora.mat[, 4]

  title <- "Metabolite Sets Enrichment Overview"
  if (length(folds) > 50) {
    folds <- folds[1:50]
    pvals <- pvals[1:50]
    title <- "Enrichment Overview (top 50)"
  }

  ht.col <- rev(heat.colors(length(folds)))

  folds <- rev(folds)
  pvals <- rev(pvals)

  plotData <- tibble(name = names(folds), fold = folds, p = pvals) %>%
    mutate(p = as.numeric(p), fold = as.numeric(folds)) %>%
    mutate(name = factor(name, levels = unique(name)))

  print(plotData)

  parent <- "./"

  top <- 1
  left <- 3
  right <- 0.6

  p <- ggplot(plotData, mapping = aes(x = name, y = fold)) +
    ylab("Fold Enrichment") +
    xlab("") +
    theme_bw(base_size = 8.8, base_family = baseFamily) +
    theme(axis.text.x = element_text(size = 10, hjust = 1, vjust = 1), legend.position = 'right',
          legend.text = element_text(size = 9), legend.title = element_text(size = 11), axis.text.y = element_text(size = 10),
          axis.title.y = element_text(size = 11),
          axis.title.x = element_text(size = 12, margin = margin(t = 0.5, b = 0, unit = 'cm')),
          panel.grid.major.x = element_blank(),
          panel.border = element_blank(), panel.grid.minor.x = element_blank(), panel.grid.major.y = element_blank(),
          plot.margin = unit(c(top, right, 0.5, left), "cm"),
          plot.title = element_text(hjust = 0.5, size = 15, face = "bold", margin = margin(t = 0, b = 1, unit = 'cm'))
    ) +
    geom_col(aes(fill = p, show.legend = F), width = 0.6, colour = "#000000", size = 0.1) +
    scale_x_discrete(labels = GetShortNames(as.character(plotData$name))) +
    coord_flip()

  p <- getBasicPlotArg(p)

  if (!is.na(legendTitle)) {
    p <- p +
      scale_fill_gradientn(legendTitle, colors = finalColors)
  }else {
    p <- p +
      scale_fill_gradientn("", colors = finalColors)
  }

  p <- p + ggtitle(title)

  ggsave(limitsize = FALSE, imageName, p, width = width, height = height)


}


